package com.example.dlna;

import java.io.File;
import java.io.IOException;
import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.URL;
import java.util.Enumeration;

import javax.jmdns.JmDNS;
import javax.jmdns.ServiceEvent;
import javax.jmdns.ServiceInfo;
import javax.jmdns.ServiceListener;

import android.Manifest;
import android.app.Activity;
import android.content.pm.PackageManager;
import android.graphics.Paint;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import com.car.screenprojection.R;

public class MainActivity extends Activity implements ServiceListener {

	InetAddress deviceAddress = null;
	private ServiceInfo info = null;
	AirPlayClientService clientService = null;
	private JmDNS jmdns;
	private URL url;
	private Button button;
	private TextView device;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main2);

		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
			int checkPermission = this.checkSelfPermission(android.Manifest.permission.ACCESS_FINE_LOCATION);
			if (checkPermission != PackageManager.PERMISSION_GRANTED) {
				if (shouldShowRequestPermissionRationale(android.Manifest.permission.ACCESS_FINE_LOCATION)) {
					requestPermissions(new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION},101);
				} else {
					requestPermissions(new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION},101);
				}
				return;
			}
		}

		Log.e("init===2", "===");

		//读写手机状态和身份
		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
			int checkPermission = this.checkSelfPermission(android.Manifest.permission.READ_PHONE_STATE);
			if (checkPermission != PackageManager.PERMISSION_GRANTED) {
				if (shouldShowRequestPermissionRationale(android.Manifest.permission.READ_PHONE_STATE)) {
					requestPermissions(new String[]{android.Manifest.permission.READ_PHONE_STATE}, 100);
				} else {
					requestPermissions(new String[]{android.Manifest.permission.READ_PHONE_STATE}, 100);
				}
				return;
			}
		}

		Log.e("init===3", "===");

		// <!-- 写入扩展存储，向扩展卡写入数据，用于写入离线定位数据 -->
		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
			int checkPermission = this.checkSelfPermission(android.Manifest.permission.READ_EXTERNAL_STORAGE);
			if (checkPermission != PackageManager.PERMISSION_GRANTED) {
				if (shouldShowRequestPermissionRationale(android.Manifest.permission.READ_EXTERNAL_STORAGE)) {
					requestPermissions(new String[]{android.Manifest.permission.READ_EXTERNAL_STORAGE, android.Manifest.permission.WRITE_EXTERNAL_STORAGE}, 0);
				} else {
					requestPermissions(new String[]{android.Manifest.permission.READ_EXTERNAL_STORAGE, android.Manifest.permission.WRITE_EXTERNAL_STORAGE}, 0);
				}
				return;
			}
		}

		Log.e("init===4", "===");

		if (Build.VERSION.SDK_INT >= 23) {
			int checkPermission = this.checkSelfPermission(android.Manifest.permission.CAMERA);
			if (checkPermission != PackageManager.PERMISSION_GRANTED) {
				if (shouldShowRequestPermissionRationale(android.Manifest.permission.CAMERA)) {
					requestPermissions(new String[]{android.Manifest.permission.CAMERA}, 102);
				} else {
					requestPermissions(new String[]{Manifest.permission.CAMERA}, 102);
				}
				return;
			}
		}



		button = (Button) findViewById(R.id.button_DLNA);
		button.getPaint().setFlags(Paint.STRIKE_THRU_TEXT_FLAG);
		button.setText("初始化设备信息");
		device = (TextView) findViewById(R.id.text_divice);
		new Thread(new Runnable() {
			public void run() {
				if (deviceAddress == null) {
					deviceAddress = getWifiInetAddress();
				}
				if (null == jmdns) {
					try {
						jmdns = JmDNS.create(deviceAddress);
						jmdns.addServiceListener("_airplay._tcp.local.",
								MainActivity.this);
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
			}
		}).start();
		button.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				if (info != null
						&& !TextUtils.isEmpty(device.getText().toString())) {
					if (clientService != null) {
						clientService.shutdown();
						clientService = null;
					}
					clientService = new AirPlayClientService(airCall);
					try {
//						url = new URL("http://1.82.221.118/183/45/43/letv-uts/14/ver_00_22-1031466708-avc-413503-aac-32000-5974083-339598191-a4db8810f80db2515f340a178a4450ef-1457769569201.m3u8?crypt=32aa7f2e330&b=454&nlh=4096&nlt=60&bf=58&p2p=1&video_type=mp4&termid=0&tss=ios&platid=3&splatid=322&its=0&qos=3&fcheck=0&amltag=0&mltag=0&proxy=1965175626,3683667991,1778917250&uid=2883415977.rp&keyitem=GOw_33YJAAbXYE-cnQwpfLlv_b2zAkYctFVqe5bsXQpaGNn3T1-vhw..&ntm=1484564400&nkey=ba3bb74d63c86517b7c839e5136acd5b&nkey2=9b31c6a596c80658fdc5149e412a6ccc&geo=CN-23-323-1&mmsid=47652365&tm=1484546287&key=b07f25f327c417fc49e5e69ddc80fca5&playid=0&vtype=13&cvid=1381041890757&payff=0&sign=mb&dname=mobile&tag=mobile&errc=0&gn=1229&vrtmcd=107&buss=0&cips=171.221.111.169");
						url = new URL("http://v.mifile.cn/b2c-mimall-media/ed921294fb62caf889d40502f5b38147.mp4");
//						url = new URL(Environment.getExternalStorageDirectory() + "/hpplay_demo/local_media/test_video.mp4");

						clientService.playVideo(url, info);
					} catch (Exception e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					if (jmdns != null) {
						try {
							jmdns.removeServiceListener("_airplay._tcp.local.",
									MainActivity.this);
							jmdns.close();
							jmdns = null;
						} catch (Exception e) {
							// TODO: handle exception
						} finally {
							Toast.makeText(MainActivity.this, "推送到DLNA成功",
									Toast.LENGTH_LONG).show();
						}
					}
				} else {
					Toast.makeText(MainActivity.this, "正在初始化设备信息",
							Toast.LENGTH_LONG).show();
					new Thread(new Runnable() {
						public void run() {
							if (deviceAddress == null) {
								deviceAddress = getWifiInetAddress();
							}
							if (null == jmdns) {
								try {
									jmdns = JmDNS.create(deviceAddress);
									jmdns.addServiceListener(
											"_airplay._tcp.local.",
											MainActivity.this);
								} catch (IOException e) {
									// TODO Auto-generated catch block
									e.printStackTrace();
								}
							}
						}
					}).start();
				}
			}
		});
	}

	Handler handler = new Handler();

	@Override
	public void serviceAdded(final ServiceEvent event) {
		// TODO Auto-generated method stub
		Log.e("name = " + event.getName(), "info = "
				+ event.getInfo().toString());
		info = event.getInfo();
		handler.post(new Runnable() {

			@Override
			public void run() {
				// TODO Auto-generated method stub
				jmdns.requestServiceInfo(event.getType(), event.getName(), 1000);
			}
		});
	}

	@Override
	public void serviceRemoved(ServiceEvent event) {
		// TODO Auto-generated method stub
	}

	@Override
	public void serviceResolved(ServiceEvent event) {
		// TODO Auto-generated method stub
		info = event.getInfo();
		Log.e("name2 = " + event.getName(), "info = "
				+ event.getInfo().toString());
		handler.post(new Runnable() {

			@Override
			public void run() {
				// TODO Auto-generated method stub
				button.getPaint().setFlags(0);
				button.setText("投屏到DLNA");
				device.setText("Name:" + info.getName() + "\n" + "URL:"
						+ info.getURL());
			}
		});
	}

	private InetAddress getWifiInetAddress() {
		try {
			for (Enumeration<NetworkInterface> en = NetworkInterface
					.getNetworkInterfaces(); en.hasMoreElements();) {
				NetworkInterface intf = en.nextElement();
				for (Enumeration<InetAddress> enumIpAddr = intf
						.getInetAddresses(); enumIpAddr.hasMoreElements();) {
					InetAddress inetAddress = enumIpAddr.nextElement();
					if (!inetAddress.isLoopbackAddress()
							&& inetAddress instanceof Inet4Address) {
						return (inetAddress);
					}
				}
			}
		} catch (Exception e) {
			return (null);
		}
		return (null);
	}

	AirPlayClientCallback airCall = new AirPlayClientCallback() {

		@Override
		public void onStopVideoSuccess() {
			// TODO Auto-generated method stub

		}

		@Override
		public void onStopVideoError(String message) {
			// TODO Auto-generated method stub

		}

		@Override
		public void onPutImageSuccess(File file) {
			// TODO Auto-generated method stub

		}

		@Override
		public void onPutImageError(File file, String message) {
			// TODO Auto-generated method stub

		}

		@Override
		public void onPlayVideoSuccess(URL location) {
			// TODO Auto-generated method stub

		}

		@Override
		public void onPlayVideoError(URL location, String message) {
			// TODO Auto-generated method stub

		}
	};
}
